package cn.itsource.pethome.org.service.impl;

import cn.itsource.pethome.basic.service.impl.BaseServiceImpl;
import cn.itsource.pethome.org.domain.Department;
import cn.itsource.pethome.org.domain.Employee;
import cn.itsource.pethome.org.mapper.DepartmentMapper;
import cn.itsource.pethome.org.query.DepartmentQuery;
import cn.itsource.pethome.org.service.IDepartmentService;
import cn.itsource.pethome.basic.util.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void save(Department department) {
        if (department.getId() == null) {
            departmentMapper.save(department);
        }else{
            this.update(department);
        }
    }

    @Override
    public void deleteMany(List<Department> ids) {
        departmentMapper.deleteMany(ids);
    }

    public void findTree(List<Department> departments){
        if (departments.size()!=0){
            for (Department department : departments) {
                //通过parentId查询子部门列表
                List<Department> list = departmentMapper.findByParentId(department.getId());
                if (list.size()!=0){
                    //把查询值封装到children中
                    department.setChildren(list);
                    this.findTree(list);
                }
            }
        }
    };

    @Override
    public List<Department> findDepartmentTree() {
        //查询一二级部门
        List<Department> departments = departmentMapper.findOneAnd2level();
        //循环所有一级部门
        for (Department department : departments) {
            //查询所有二级部门
            List<Department> children = department.getChildren();
            //判断是否有二级部门
            if(children.size()==0){
                department.setChildren(null);
            };
            //从二级部门开始循环后面部门
            this.findTree(children);
        }
        return departments;
    }
}
